package cn.fastpay.user.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

import static cn.fastpay.core.util.RSAUtil.loadKey;

/**
 * @author freewolf
 */
public class RSAUtil {

    public static final String RSA_ALGORITHM = "RSA";

    /**
     * 从证书文件中得到私钥
     *
     * @throws Exception 证书解析失败
     */
    public static RSAPrivateKey getPrivateKey() {
        // 读取私钥
        try {
            Resource resource = new ClassPathResource("private_key.pem");
            String privateKeyStr = loadKey(resource.getInputStream());
            KeyFactory kf = KeyFactory.getInstance(RSA_ALGORITHM);
            PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyStr));
            return (RSAPrivateKey) kf.generatePrivate(keySpecPKCS8);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析私钥证书出错：[" + e.getMessage() + "]");
        }
    }
}
